from flask import Blueprint, session, render_template, redirect, request, jsonify, abort
from flask_login import LoginManager, login_required, login_user, logout_user, current_user
from datetime import timedelta
from web_views import web_view
from role_check import get_all_cn, get_all_cn_details, update_cn_scope
from models import User
from utilities.ldap_helper import LDAPLogin
from urllib2 import unquote
from utilities.log_helper import logger

user = Blueprint('user', __name__)

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = '/login'
login_manager.remember_cookie_duration = timedelta(days=1)


@user.route('/role')
@login_required
def role_control():
    role = current_user.get_cn()

    def get_web_view():
        role_s = get_all_cn()[role]
        if len(role_s) == 1 and role_s[0] == 'all':
            return web_view
        tmp_dict = {}
        for s in role_s:
            tmp_dict[s] = web_view[s]
        return tmp_dict

    tmp_dict1 = get_web_view()
    return jsonify(data=tmp_dict1)


@user.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        login_flag, cn = LDAPLogin(request.form['username'], request.form['password'])
        if login_flag:
            user_instance = User(request.form['username'], request.form['password'], cn)
            if 'remember' in request.form:
                login_user(user_instance, remember=True)
            else:
                login_user(user_instance)
            session.permanent = True
            user.permanent_session_lifetime = timedelta(minutes=100)

            referrer = request.referrer
            if '?next=' in referrer:
                return redirect(unquote(referrer[referrer.index('?next=') + 6:]))
            return redirect('/index')
        else:
            message = 'Invalid username/password'
            return render_template('login.html', message=message)
    return render_template('login.html')


@login_manager.user_loader
def load_user(user_id):
    if user_id:
        name, cn = user_id.split(',')
        return User(name=name, cn=cn)
    user = User()
    return user


@user.route('/logout', methods=['GET', 'POST'])
@login_required
def logout():
    logout_user()
    return redirect('/login')


@user.route('/')
@user.route('/index')
@login_required
def hello_world():
    return render_template('index.html', name=current_user.get_name())


@user.route('/admin')
@login_required
def admin():
    if current_user.get_name() in ['shenguocheng', 'liumiao']:
        return render_template('admin.html')
    else:
        abort(401)


@user.route('/get_cn_details')
@login_required
def get_cn_details():
    return jsonify(data=get_all_cn_details())


@user.route('/blank')
def blank():
    return render_template('blank.html')


@user.route('/update_scope')
@login_required
def update_scope():
    a = request
    scope = request.args['scope']
    cn = request.args['cn']
    return update_cn_scope(scope, cn)
